package com.xianggu.spring.transaction.config;

import com.xianggu.mybatis.mysql.DruidExample;
import com.xianggu.spring.transaction.context.TransactionContext;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class TransactionManager {
    // 开启事务
    public void begin() throws SQLException {
        System.out.println("开启事务");
        Connection connection = TransactionContext.getConnection();
        if (connection == null) {
            connection = DruidExample.getConnection();
        }
        // 关闭自动提交
        connection.setAutoCommit(false);
        // 将连接绑定到当前线程
        TransactionContext.setConnection(connection);
    }

    // 提交事务
    public void commit() throws SQLException {
        System.out.println("提交事务");
        Connection connection = TransactionContext.getConnection();
        if (connection != null && !connection.isClosed()) {
            connection.commit(); // 提交事务
            connection.close();  // 关闭连接
            TransactionContext.removeConnection(); // 解绑连接
        } else {
            throw new SQLException("数据库连接已关闭！请检查");
        }
    }

    // 回滚事务
    public void rollback() {
        System.out.println("回滚事务");
        Connection connection = TransactionContext.getConnection();
        if (connection != null) {
            try {
                connection.rollback(); // 回滚事务
                connection.close();   // 关闭连接
            } catch (SQLException e) {
                e.printStackTrace();
            }
            TransactionContext.removeConnection(); // 解绑连接
        }
    }
}